package com.ellecity06.debugtools.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.ellecity06.debugtools.databinding.ActivityDebugBaseBinding
import com.gyf.immersionbar.ktx.statusBarHeight
import java.lang.reflect.ParameterizedType

/**
 * @author ellecity06
 * @time 2023/4/19 15:07
 * @des
 */
abstract class BaseDebugFragment<VB : ViewBinding, out VM : BaseDebugViewModel> : Fragment() {
    protected val viewModel: VM by lazy { initViewModel() }
    private var isLoaded = false
    private var _binding: VB? = null
    protected lateinit var baseBinding: ActivityDebugBaseBinding
    protected lateinit var binding: VB
    override fun onResume() {
        super.onResume()
        if (!isLoaded && !isHidden) {
            lifecycleScope.launchWhenCreated {
                lazyInit()
            }
            isLoaded = true
        }
    }

    abstract fun lazyInit()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        baseBinding = ActivityDebugBaseBinding.inflate(inflater, container, false)
        _binding = inflateBinding(inflater, container)
        val layoutParams = baseBinding.statusView.layoutParams
        layoutParams.height = statusBarHeight
        baseBinding.statusView.layoutParams = layoutParams
        baseBinding.layoutContent.addView(_binding!!.root)
        binding = _binding!!
        return baseBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initBaseEvent()
    }

    private fun initBaseEvent() {
        baseBinding.ivBack.setOnClickListener { requireActivity().finish() }
    }

    open fun initView() = Unit


    abstract fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): VB
    override fun onDestroyView() {
        super.onDestroyView()
        isLoaded = false
    }

    open fun initViewModel(): VM {
        val type = javaClass.genericSuperclass
        return if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[1]
            val tClass = tp as? Class<VM> ?: BaseDebugViewModel::class.java
            ViewModelProvider(this)[tClass] as VM
        } else {
            ViewModelProvider(this)[BaseDebugViewModel::class.java] as VM

        }
    }
}